package controllers

import (
	"NewEdu/models"
	"NewEdu/utils"
	"strings"
	"time"

	"github.com/beego/beego/v2/server/web/context"

	"github.com/dgrijalva/jwt-go"
)

// FilterUser 过滤钩子
func FilterUser(ctx *context.Context) {

	switch {
	case strings.Index(ctx.Request.URL.Path, "/api/user/login") == 0:
		fallthrough
	case strings.Index(ctx.Request.URL.Path, "/api/user/register") == 0:
		return
	default:
	}

	token := new(jwt.Token)
	token.Valid = false
	var err error
	var authString = ctx.Input.Header("Authorization")
	if authString != "" {
		token, err = jwt.Parse(authString, func(token *jwt.Token) (interface{}, error) {
			return []byte(utils.GetJWTSecret()), nil
		})
		if err != nil {
			resultData := utils.Export(401, "登录状态异常,请重新登录", nil)
			ctx.Output.JSON(resultData, false, false)
			return
		}
	}
	if !token.Valid {
		resultData := utils.Export(402, "登录状态异常,请重新登录", nil)
		ctx.Output.JSON(resultData, false, false)
		return
	}
	userinfo, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		resultData := utils.Export(401, "token无效", nil)
		ctx.Output.JSON(resultData, false, false)
		return
	}
	if userinfo["sn"] == nil || userinfo["sn"] == "" {
		resultData := utils.Export(400, "token无效", err)
		ctx.Output.JSON(resultData, false, false)
		return
	}
	var user models.TUser
	user.Sn = userinfo["sn"].(string)
	user.Name = userinfo["name"].(string)
	expireTime := userinfo["exp"].(float64)

	if int(expireTime) <= int(time.Now().Unix()) {
		resultData := utils.Export(400, "登陆已经过期", "请重新登陆")
		ctx.Output.JSON(resultData, false, false)
		return
	}

	if userinfo["r"] != nil {
		temp := userinfo["r"].(float64)
		user.Role = int8(temp)
	}

	ctx.Input.SetData(models.CurrentUser, &user)

}
